<?php
include_once "../../qc_base.php";
include_once "../../qc_utils.php";
include_once "../../bootstrap.php";

include_once "../../classes/MakePage.php";


function makesuredir($dir){
	if(!file_exists(dirname($dir))){
		makesuredir(dirname($dir));
	}
	if(!file_exists($dir)){
		mkdir($dir);
	}
}



	$q = Doctrine_Query::create()
	->from('Crudsets cs')
	->innerJoin('cs.Crudcols cc')
	->leftJoin('cs.Projects pro')	
	->leftJoin('cc.VarInfo v')
	->Where('crudset_id = ?',$crudset_id);

	$ar_info = $q->execute()->toArray(true);
	print '<pre>';
	print_r($ar_info);
	print '</pre>';



/*
--------------- Structure Data Format in Array $ar_info  (With Example Data)
(Each Row of Crudsets)	
        (
            [crudset_id] => 6
            [cs_name] => payments
            [paging] => 0
            [sorting] => 1
            [filter] => 1
            [main_table] => 82
            [project_id] => 1
            [query] => 
            [cs_type] => inline_edi
            [list_base_name] => def_list
            [proc_base_name] => CFprocess
            [process_class] => process
            [class_base_name] => CF_AJTable
            [html_table_name] => html_table
            [class_name] => CListSpecial
            [list_table_instance] => tableinstance
            [proc_class_instance] => process
            [edit_base_class] => CFform
            [edit_class_name] => FormClass
            [edit_instance] => TheForm
            [edit_page_name] => 
            [multiact] => 0
            [css_file] => commonctls.css
            [showbuttons] => sd
            [subdirectory] => payments/
            [needs_login] => 0
            [Crudcols] => Array
                ( Each CrudCol )
                    [0] => Array
                        (
                            [crudcol_id] => 637
                            [crudset_id] => 6
                            [variable_id] => 599
                            [is_key] => 1
                            [shown_in_list] => 1
                            [edit_in_list] => 0
                            [edit_type] => text
                            [filter] => 1
                            [showfilter] => 0
                            [restrict] => 0
                            [is_sort] => 0
                            [header_name] => 
                            [is_add] => 0
                            [list_query] => 
                            [list_keycol] => 
                            [list_showcol] => 
                            [size] => 20
                            [rows] => 1
                            [col_order] => 0
                            [makefunction] => 
                            [Crudsets] => 
                            [VarInfo] => Array
                                (
                                    [variable_id] => 599
                                    [variable_name] => customerNumber
                                    [type] => int(11)
                                    [quote] => 
                                    [project_id] => 1
                                    [variable_size] => 
                                    [source_id] => 82
                                    [def_show_text] => 
                                    [is_key] => 1
                                )

                        )

                )
			
            [Projects] => Array
                (
                    [project_id] => 1
                    [project_name] => sampletest1
                    [def_function_page] => 
                    [project_path] => sampletest1
                    [project_server] => localhost
                    [project_db] => sampledb
                    [project_login] => root
                    [project_pass] => 
                    [class_subpath] => CFClass
                    [user_table_name] => users
                    [up_table_name] => users_pages
                    [dbmethod] => pdo
                    [dbtype] => mysql
                    [template_dir] => templates/default/
                    [file_structure] => standard_pdo
                )

        )

)

*/



	$structure_path = QC_SYS_BASEDIR . '/structures/';
	
	include $structure_path . $structure .'/paths.php';
	

	$outpath = $paths['modules'];
	$outpath = str_replace('<setname>',$ar_info['cs_name'],$outpath);
	
	$outpath = QC_SYS_BASEDIR . '/' . QC_PROJECT_SUBPATH . $ar_info['Projects']['project_name'] . '/' . $outpath ;

	makesuredir($outpath);
	
	
	$targetfile = $outpath . $ar_info['cs_name'] . '_htlist.php';
	$tplfile = 'pdoaj_htlist_tpl.php';
	echo 'OUTPUT TO: ' . $targetfile;

//--------------------Create Replacement Text
//--------------------------------------------------------------------------------------------------


	function write_columns($ar_info,$col_array_name){
		$js_cols = "var $col_array_name = [\n";
		$divider = "";
		foreach($ar_info['Crudcols'] AS $colnum=>$colinfo){
			$column = $colinfo['Varinfo']['variable_name'];
			
		
			if(!empty($colinfo['shown_in_list'])){
				$js_cols .= $divider . write_column($ar_info,$colnum);
				$divider = ",\n";
			}
		}
		$js_cols .= "\n];\n";
		return $js_cols;
	}
	
	
	function write_column($ar_info,$colnum){
		$colinfo = $ar_info['Crudcols'][$colnum];
		$column = $colinfo['Varinfo']['variable_name'];
		$js_col = '{';
		$js_col .= 'id:"' . $column . '" ';
		(isset($colinfo['header_name']))?$js_col .= ', name:"' . $colinfo['header_name'] . '" ':$js_col .= ', name:"' . $column . '" ';
		$js_col .= ', field:"' . $column . '" ';
		if(isset($colinfo['size'])){$js_col .= ', width:"' . $colinfo['size'] * 6 . '" ';}
		if($colspec['show'] == 'E'){
			if($colinfo['edit_type'] == 'text'){$js_col .= ', editor: TextCellEditor ';}
			if($colinfo['edit_type'] == 'textarea'){$js_col .= ', editor: LongTextCellEditor ';}
			if($colinfo['edit_type'] == 'calendar'){$js_col .= ', formatter: DateCellFormatter, 
editor: DateCalendarEditor , DateSourceFormat: "yy-mm-dd" , DateShowFormat: "mm/dd/yy" ';}	
			if($colinfo['edit_type'] == 'checkbox'){$js_col .= ', formatter: BoolCellFormatterTF, editor: BoolCheckboxCellEditor , 
truefalse: {istrue: 1, isfalse: 0} 	';}		
			if($colinfo['edit_type'] == 'querylist'){$js_col .= ", editor: LookupListEditor , 
formatter: LookupListFormatter, lookupList: " . $ar_info['cs_name'] . "_lookup['$column'], lookupIndex: " . $ar_info['cs_name'] . "_lookup_idx['$column'] ";}			
		}
		$js_col .= '}';
		return $js_col;
	}

	function write_options($ar_info,$opt_array_name){
		$js_opt = "var $opt_array_name = {\n";
		
		$js_opt .= "		editable: true,\n";
		$js_opt .= "		enableAddRow: false,\n";
		$js_opt .= "		enableCellNavigation: true,\n";
		$js_opt .= "		asyncEditorLoading: false,\n";
		$js_opt .= "		editCommandHandler: " . $ar_info['cs_name'] . "_QandX\n";		
		
		$js_opt .= "};\n";
	
		return $js_opt;
	}
	
function write_js_item_key_value($ar_info){
	$predelimiter = "";
	foreach($ar_info['Crudcols'] AS $colnum=>$colinfo){
			$column = $colinfo['Varinfo']['variable_name'];
		if(!empty($colinfo['is_key'])){
			$js .= $predelimiter . "item['$column']";
			$predelimiter = " + ',' + ";
		}
	}
	return $js;
}

function write_js_item_key_set($ar_info){
	$predelimiter = "";
	foreach($ar_info['Crudcols'] AS $colnum=>$colinfo){
			$column = $colinfo['Varinfo']['variable_name'];
	
	
		if(!empty($colinfo['is_key'])){
			$js .= $predelimiter . $column;
			$predelimiter = " + ',' + ";
		}
	}
	return $js;
}
	
function write_js($ar_info){


	$actionpage = $ar_info['cs_name'] . '/' . $ar_info['cs_name'] . '_proc.php';
	$prefixparamstring = '';

	$tbl_js = '';
	$tbl_js .= 'var ' . $ar_info['cs_name'] . '_grid;
			var ' . $ar_info['cs_name'] . '_data = [];		
			var ' . $ar_info['cs_name'] . '_lookup = [];
			var ' . $ar_info['cs_name'] . '_lookup_idx = [];';


	$tbl_js .= '
			$(function()
			{
			';
			
				
	$tbl_js .= '
			var commandQueue = [];			
			$.ajaxSetup({cache: false});
	';


		foreach($ar_info['Crudcols'] AS $colnum=>$colinfo){
			$column = $colinfo['Varinfo']['variable_name'];
			if($colinfo['edit_type'] == 'querylist'){
				$tbl_js .= '
	 $.ajax({  
	   url: "'. $actionpage . '?mode=jsonlookup&sel=' . $ar_info['cs_name'] . '&col=' . $column . '",  
	   dataType: "json",  
	   async: false,  
	   success: function(data){  
			var thisindex = [];
				' . $ar_info['cs_name'] . '_lookup["' . $column . '"] = data;
				for(x in ' . $ar_info['cs_name'] . '_lookup["' . $column . '"]){
					thisindex[' . $ar_info['cs_name'] . '_lookup["' . $column . '"][x].keyvalue] = ' . $ar_info['cs_name'] . '_lookup["' . $column . '"][x].showvalue;
				}
				' . $ar_info['cs_name'] . '_lookup_idx["' . $column . '"] = thisindex;
				}
			});	
	';


			}
		}
	



	$tbl_js .='
			
			function ' . $ar_info['cs_name'] . '_QandX(item,column,editCommand) {
				commandQueue.push(editCommand);
				$.get("' . $actionpage   . '",{sel: "' . $ar_info['cs_name'] . '", mode: "update", ks: "' . write_js_item_key_set() . '", kv: ' . write_js_item_key_value() . ', field: column.field, value: editCommand.serializedValue},   function(data){
		 if(data.status == "OK"){
				editCommand.execute();
		 }else{
				alert("Data Sync Error: " + data.msg);
		 }
	   },"json");

			}



			function ' . $ar_info['cs_name'] . '_undo() {
				var command	 = commandQueue.pop();
				if (command && Slick.GlobalEditorLock.cancelCurrentEdit()) {
					command.undo();
					grid.gotoCell(command.row,command.cell,false);
				}
			}
			
				
	';
		
	$tbl_js .= write_columns($ar_info,'columns');



	$tbl_js .= write_options($ar_info,'options');	
							
	$tbl_js .= '		
		
				//retrieve comments to display on page
				$.getJSON("' . $actionpage . $prefixparamstring . '&jsoncallback=?", function(' . $ar_info['cs_name'] . '_data) { 
	';


			
			
			
	$tbl_js .= '
			
					' . $ar_info['cs_name'] . '_grid = new Slick.Grid($("#' . $ar_info['cs_name'] . '_grid"), ' . $ar_info['cs_name'] . '_data, columns, options);

					});


				
			});	
	';
	return $tbl_js;

}



//--------------------------------------------------------------------------------------------------




$setcsname = '
// SET THE NAME 
'."\$name = '" . $ar_info['cs_name'] . "';";

//$tablesetup = '
//$' . $ar_info['cs_name'] . '_grid = new CF_TableSlick($' . $ar_info['cs_name'] . '_spec,"","' . $ar_info['cs_name'] . '");
//$' . $ar_info['cs_name'] . '_grid->set_actionpage("' . $ar_info['cs_name'] . '/' . $ar_info['cs_name'] . '_proc.php");
//';

$tablesetup = write_js($ar_info);

//$tableprint = 'print $' . $ar_info['cs_name'] . '_grid->maketable();';
$tableprint = '<div id="' . $ar_info['cs_name'] . '" ></div>' . "\n";

//---------------------------Write into file	
	
	

	$pagemaker = new MakePage();

//	$pagemaker->AddReplacement('includefieldspec',$includefieldspec);
	$pagemaker->AddReplacement('setcsname',$setcsname);	
	$pagemaker->AddReplacement('tablesetup',$tablesetup);
	$pagemaker->AddReplacement('tableprint',$tableprint);	
	
	$newstuff = $pagemaker->ReplaceInFile($tplfile,$targetfile);
	
	$pagemaker->PrintReplacementsTable();

	echo '<pre>' . $pagemaker->str_log . '</pre>';
	
	file_put_contents($targetfile,$newstuff);	

	return $newstuff;



?>
